#include "pch.h"
#include "include/protocol.h"

std::unordered_map<UINT32, CProtocol*>	CProtocol::sm_oPtcMap;
//-------------------------------------------------------------------------------------

CProtocol::CProtocol(UINT32 dwType)
{
	this->m_dwType = dwType;
	m_debug = false;
	m_Compress = false;
	m_sessionID = 0;
	m_message = NULL;
}

CProtocol::~CProtocol()
{

}

int  CProtocol::Serialize(void* data, int len) const
{
	if (!m_message)
	{
		return 0;
	}
	if (!m_message->SerializeToArray(data, len))
	{
		return -1;
	}
	return m_message->ByteSize();
}

bool CProtocol::DeSerialize(const void* data, int len)
{
	if (!m_message || len == 0)
	{
		return true;
	}
	return m_message->ParseFromArray(data, len);
}

void CProtocol::SetDontCompress()
{

}

void CProtocol::DebugPrint()
{

}

bool CProtocol::Register(CProtocol* poProtocol, bool debug/* = false*/)
{
	if (!poProtocol)
	{
		return false;
	}
	UINT32 dwType = poProtocol->m_dwType;
	CProtocolMap::iterator it = sm_oPtcMap.find(dwType);
	if (it != sm_oPtcMap.end())
	{
		return false;
	}
	sm_oPtcMap[dwType] = poProtocol;
	return true;
}

static std::unordered_map< UINT32, const char*> all_ptc_names;
void CProtocol::UnRegister()
{
	sm_oPtcMap.clear();
	all_ptc_names.clear();
}

CProtocol* CProtocol::GetProtocol(UINT32 dwType)
{
	CProtocolMap::iterator it = sm_oPtcMap.find(dwType);
	if (it != sm_oPtcMap.end())
	{
		return it->second;
	}
	return NULL;
}


void CProtocol::RegistProtoName(UINT32 dwType, const char* Name)
{
	all_ptc_names[dwType] = Name;
}

const char* CProtocol::GetProtoName(UINT32 dwType)
{
	std::unordered_map< UINT32, const char*>::iterator it = all_ptc_names.find(dwType);
	if (it != all_ptc_names.end())
	{
		return it->second;
	}
	return "not found protocol name";
}
